package com.spr.controller;

import java.util.Date;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.spr.exception.*;
import com.spr.model.Application;
import com.spr.model.Faculty;
import com.spr.model.Position;
import com.spr.model.Register;
import com.spr.model.Schedule;
import com.spr.model.Student;
import com.spr.model.StudentRegister;
import com.spr.model.User;
import com.spr.service.*;

@Controller
@RequestMapping(value="/register")
public class RegisterController {
	
	 @Autowired
     private PositionService positionService;
	 
	 @Autowired
	 private FacultyService facultyService;
	 
	 @Autowired
	 private ScheduleService scheduleService;
     
	 
	 @Autowired
	 private StudentService studentService;
	 
	 @Autowired
	 private ApplicationService applicationService;

	
  @RequestMapping(value="/create", method=RequestMethod.GET)
    public ModelAndView newPositionPage() {
            ModelAndView mav = new ModelAndView("register-new", "register", new Register());
            return mav;
    }
    
    @RequestMapping(value="/create", method=RequestMethod.POST)
    public ModelAndView createNewRegister(@ModelAttribute  @Valid Register register,
                    BindingResult result,
                    final RedirectAttributes redirectAttributes) throws FacultyNotFound, ScheduleNotFound, RegisterNotFound {
            
            
            ModelAndView mav = new ModelAndView();
            Position position = register.getPosition();
          
            Schedule schedule = scheduleService.create(register.getSchedule());
           
           // Faculty faculty = facultyService.update(register.getFaculty());
           // facultyService.update(faculty);
            
            position.setScheduleID(schedule.getScheduleID());
            position.setFacultyID(1);
            positionService.create(position);
            
            mav.setViewName("redirect:/register/list.html");
                                 
            return mav;                
    }
	
	@RequestMapping(value="/list/{studentID}/{scheduleID}", method=RequestMethod.GET)
	public ModelAndView listPositionsForStudentsPage(@PathVariable Integer studentID, @PathVariable Integer scheduleID, HttpSession session){

		StudentRegister s = new StudentRegister();
		
		s.setStudent(studentService.findById(studentID));
		
		s.setSchedule(scheduleService.findById(scheduleID));
		
		ModelAndView mav = new ModelAndView("register-list");
		List<Position> positionList = positionService.findAll();
        ArrayList<Position> temp = timeList(positionList, s);
        User user = (User) session.getAttribute("UserDetails");
		
        mav.addObject("type", user.getType());
        mav.addObject("positionList", temp);
        return mav;
	}
	@RequestMapping(value="/list", method=RequestMethod.GET)
	public ModelAndView listAllPositions(HttpSession session){

		ModelAndView mav = new ModelAndView("register-list");
		List<Position> positionList = positionService.findAll();
   
		User user = (User) session.getAttribute("UserDetails");
		mav.addObject("type", user.getType());
        mav.addObject("positionList", positionList);
        return mav;
	}
	
	@RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
	public ModelAndView editRegisterPage(@PathVariable Integer id, HttpSession session) {
		Register r = new Register();
		
		Position z = positionService.findById(id);
		r.setPosition(z);
		Schedule schedule = scheduleService.findById(z.getScheduleID());
		r.setSchedule(schedule);
		ModelAndView mav = new ModelAndView("register-edit", "register", r);
		mav.addObject("position", positionService.findById(id));
		mav.addObject("schedule",scheduleService.findById(z.getScheduleID()));
		return mav;
	}

	@RequestMapping(value = "/edit/{id}", method = RequestMethod.POST)
	public ModelAndView editstudent(@ModelAttribute @Valid Register register,
			BindingResult result, @PathVariable Integer id,
			final RedirectAttributes redirectAttributes, HttpSession session) throws ScheduleNotFound, RegisterNotFound {
		//
		// if (result.hasErrors())
		// return new ModelAndView("student-edit");
		
		User u = (User) session.getAttribute("UserDetails");
		
		Position position = register.getPosition();
		position.setPositionID(id);
		position = positionService.findById(id);
		register.getSchedule().setScheduleID(position.getScheduleID());
		position.setFacultyID(1);
		position.setScheduleID(position.getScheduleID());
	
		ModelAndView mav = new ModelAndView("register-view", "register", register);
		
		
		mav.addObject("position", register.getPosition());
		mav.addObject("schedule", register.getSchedule());
		mav.addObject("type", u.getType());
		scheduleService.update(register.getSchedule());
		positionService.update(position);
		
		return mav;
	}
	
	@RequestMapping(value="/view/{id}", method=RequestMethod.GET)
	public ModelAndView viewRegisterPage(@PathVariable Integer id, HttpSession session){
		ModelAndView mav = new ModelAndView("register-view");
        Position position = positionService.findById(id);
        Faculty faculty = facultyService.findById(position.getFacultyID());
        Schedule schedule = scheduleService.findById(position.getScheduleID());
        User user = (User) session.getAttribute("UserDetails");
        
        List<Student> studentList = applicationService.getStudentsByPositionID(id);
        
        mav.addObject("type", user.getType());
        mav.addObject("position", position);
        mav.addObject("studentList", studentList);
        mav.addObject("schedule", schedule);
        return mav;
	}
    
    @RequestMapping(value="/delete/{id}", method=RequestMethod.GET)
    public ModelAndView deleteRegister(@PathVariable Integer id,
                    final RedirectAttributes redirectAttributes) throws RegisterNotFound, ScheduleNotFound{ 
            
    		Position position = positionService.findById(id);
    		int schedule = position.getScheduleID();
    		scheduleService.delete(schedule);
            position = positionService.delete(id);
            
            ModelAndView mav = new ModelAndView("redirect:/register/list.html");     

            return mav;
    }
	
	public ArrayList<Position> timeList(List<Position> list, StudentRegister schedule){
		ArrayList<Position> finalList = new ArrayList<Position>();
		
		
		for(Position job : list){
			Schedule b = scheduleService.findById(job.getScheduleID());
			if((schedule.getSchedule().getSundayFrom().before(b.getSundayFrom()) && (schedule.getSchedule().getSundayTo().after(b.getSundayTo())))){
				finalList.add(job);
			}
			else if((schedule.getSchedule().getMondayFrom().before(b.getMondayFrom()) && (schedule.getSchedule().getMondayTo().after(b.getMondayTo())))){
				finalList.add(job);
			}
			else if((schedule.getSchedule().getTuesdayFrom().before(b.getTuesdayFrom()) && (schedule.getSchedule().getTuesdayTo().after(b.getTuesdayTo())))){
				finalList.add(job);
			}
			else if((schedule.getSchedule().getWednesdayFrom().before(b.getWednesdayFrom()) && (schedule.getSchedule().getWednesdayTo().after(b.getWednesdayTo())))){
				finalList.add(job);
			}
			else if((schedule.getSchedule().getThursdayFrom().before(b.getThursdayFrom()) && (schedule.getSchedule().getThursdayTo().after(b.getThursdayTo())))){
				finalList.add(job);
			}
			else if((schedule.getSchedule().getFridayFrom().before(b.getFridayFrom()) && (schedule.getSchedule().getFridayTo().after(b.getFridayTo())))){
				finalList.add(job);
			}
			else if((schedule.getSchedule().getSaturdayFrom().before(b.getSaturdayFrom()) && (schedule.getSchedule().getSaturdayTo().after(b.getSaturdayTo())))){
				finalList.add(job);
			}
		}
		return finalList;
	}
}
